<?php defined('SYSPATH') or die('No direct access allowed.');

class Controller_Admin_Catalogue extends Controller_Admin_Template
{
   
    public function after()
    {
        
        $this->template->styles = array('css/admin/ui-lightness/jquery-ui-1.8.16.custom.css' => 'screen',
                                        'css/admin/fileuploader.css' => 'screen');
        $this->template->scripts = array('js/jquery-ui-1.8.16.custom.min.js',
                                         'js/fileuploader.js');
        
        parent::after();
    }
    
    public function action_index()
    {
        $catalogues = View::factory('admin/catalogue/catalogue')
                        ->set('catalogues', $this->get_catalogues());
        $this->template->content = $catalogues->render();        
    }
    
    public function get_catalogues($parent_id = 0, $path = '')
    {
        $catalogues = array();
        $result = DB::query(Database::SELECT, "SELECT c1.id as `id`, c1.name as `name`, c1.href as `href`, 
                                                      c1.hide as `hide`, c1.parent_id as `parent_id`, 
                                                      (COUNT( c2.name )>0) as `subcatalogues` 
                                                FROM  `catalogues` AS  `c1` 
                                                LEFT JOIN  `catalogues` AS  `c2` ON c2.parent_id = c1.id
                                                WHERE c1.parent_id =:parent_id                                               
                                                GROUP BY c1.name
                                                ORDER BY c1.pos")
                    ->param(':parent_id', $parent_id)
                    ->execute();        
        foreach ($result as $catalogue) {
            $catalogue['href'] = $path.$catalogue['href'];
            $catalogue['products'] = 0;
            
            if($catalogue['subcatalogues']){
                $catalogue['subcatalogues'] = $this->get_catalogues($catalogue['id'], $catalogue['href']);
                foreach($catalogue['subcatalogues'] as $subcatalogue)
                    $catalogue['products'] += $subcatalogue['products'];
            } else {
                unset($catalogue['subcatalogues']);
                $catalogue['products'] = DB::query(Database::SELECT, "SELECT COUNT(*) as `count` FROM `products` 
                                                                   WHERE catalogue_id=:catalogue_id")
                                         ->param(':catalogue_id', $catalogue['id'])
                                         ->execute()
                                         ->get('count');            
            }
            
            $catalogues[] = $catalogue;
        }
        return $catalogues;
    }
    
    public function action_add()
    {
        $this->template->content = View::factory('admin/catalogue/form')
                                        ->set('title', 'Добавление каталога')
                                        ->set('catalogue', array('parent_id' => Arr::get($_REQUEST, 'id', 0)));  
    }
    
    public function action_hide()
    {
        $id = Arr::get($_REQUEST, 'id', -1);
        if($id != -1){
            $hide = ORM::factory('catalogue', $id)->__get('hide');
            if($hide == 'hide')
                $this->show($id);
            else
                $this->hide($id);
        }
        
        Request::$initial->redirect('admin/catalogue');
    }
    
    public function hide($id)
    {
        ORM::factory('catalogue', $id)->set('hide','hide')->save();
           
        $catalogues = ORM::factory('catalogue')->where('parent_id', '=', $id)->find_all();
        foreach ($catalogues as $catalogue){
            $this->hide($catalogue->id);
        }    
    }
    
    public function show($id)
    {
        if($id != 0){
            $catalogue = ORM::factory('catalogue', $id);
            $catalogue->hide = 'show';
            $catalogue->save();
            
            $this->show($catalogue->parent_id);
        }
    }
    
    public function action_save()
    {
        $this->auto_render = false;
        
        $id = Arr::get($_POST, 'id', NULL);
        
        if(!empty($id)){
            $catalogue = ORM::factory('catalogue', $id)
                            ->values($_POST);
            
        } else {
            $catalogue = ORM::factory('catalogue')
                            ->values($_POST);
        }
        
        try
        {           
            $catalogue->save();
            
            if(empty($id)){
                $catalogue->pos = DB::query(Database::SELECT, "SELECT MAX(pos) + 1 as `pos`
                                                             FROM `catalogues`
                                                             WHERE `parent_id`={$catalogue->parent_id}")
                                    ->execute()
                                    ->get('pos');                          

                $catalogue->save();
            }

            $response = array('status' => 'ok');
        }
        catch(Kohana_ORM_Validation_Exception $e)
        {
            $errors = $e->errors('/admin');
            $response = array('status' => 'error',
                              'error' => $errors);
        }
     
        $this->response->body(json_encode($response)); 
 
    }
    
    public function action_delete()
    {
        $this->delete(Arr::get($_REQUEST, 'id', 0));
        
        Request::$initial->redirect('admin/catalogue');
    }
    
    public function delete($id)
    {
        if($id != 0)
        {
            $catalogues = DB::query(Database::SELECT, "SELECT `id` FROM `catalogues` WHERE `parent_id`=:parent_id")
                            ->param(':parent_id', $id)
                            ->as_object()
                            ->execute();
            
            foreach ($catalogues as $catalogue) {
                $this->delete($catalogue->id);
            }
            
            $fp = fopen($_SERVER['DOCUMENT_ROOT'].'/debug.txt', 'a+');
            fwrite($fp, "delete $id \r\n");
            fclose($fp);
            
            ORM::factory('catalogue', $id)->delete();
            
           
        }
    }
    
    public function action_up()
    {
        $id = Arr::get($_REQUEST, 'id', 0);
        if($id != 0) {
            $catalogue = ORM::factory('catalogue', $id);
            
            $query = DB::query(Database::SELECT, "SELECT `id`, `pos`
                                                  FROM `catalogues`
                                                  WHERE (`pos` < {$catalogue->pos} AND `parent_id`={$catalogue->parent_id})
                                                  ORDER BY `pos` DESC
                                                  LIMIT 1");
            
            $result = $query->execute();
            if($result->count() > 0){
                $up_id = $result->get('id');
                $up_pos = $result->get('pos');
                
                $up_catalogue = ORM::factory('catalogue', $up_id);
                $up_catalogue->pos = $catalogue->pos;
                $up_catalogue->save();
                
                $catalogue->pos = $up_pos;
                $catalogue->save();
            }
        }
        
        Request::$initial->redirect('admin/catalogue');
    }
    
    public function action_down()
    {
        $id = Arr::get($_REQUEST, 'id', 0);
        if($id != 0) {
            $catalogue = ORM::factory('catalogue', $id);
            
            $query = DB::query(Database::SELECT, "SELECT `id`, `pos`
                                                  FROM `catalogues`
                                                  WHERE (`pos` > {$catalogue->pos} AND `parent_id`={$catalogue->parent_id})
                                                  ORDER BY `pos` ASC
                                                  LIMIT 1");
            
            $result = $query->execute();
            if($result->count() > 0){
                $down_id = $result->get('id');
                $down_pos = $result->get('pos');
                
                $down_catalogue = ORM::factory('catalogue', $down_id);
                $down_catalogue->pos = $catalogue->pos;
                $down_catalogue->save();
                
                $catalogue->pos = $down_pos;
                $catalogue->save();
            }
        }
        
        Request::$initial->redirect('admin/catalogue');
    }
    
    public function action_edit()
    {
        $id = Arr::get($_REQUEST, 'id', -1);       

        $catalogue = ORM::factory('catalogue', $id);
        if($catalogue->loaded()){           
            $catalogue = $catalogue->as_array();
        
            $this->template->content = View::factory('admin/catalogue/form')     
                                           ->set('title', 'Редактирование статьи')
                                           ->set('catalogue', $catalogue);
                                           
        } else        
            Request::$initial->redirect('admin/catalogue');
    }
    
    public function action_product()
    {
    	$catalogue_id = Arr::get($_REQUEST, 'id', 0);
    	
    	$count = DB::query(Database::SELECT, "SELECT COUNT(*) as `count` FROM `products`
    										  WHERE `catalogue_id`=:catalogue_id")
    				->param(':catalogue_id', $catalogue_id)
                    ->execute()
                    ->get('count');
        
  		$pagination = Pagination::factory(array('total_items' => $count,
  												'items_per_page' => 50));
    	
    	$products = DB::query(Database::SELECT, "SELECT * FROM `products`
    										     WHERE `catalogue_id`=:catalogue_id
    										     ORDER BY `name` ASC
    										     LIMIT :offset, :limit")
        				->param(':catalogue_id', $catalogue_id)                
    					->param(':offset', $pagination->offset)
                        ->param(':limit', $pagination->items_per_page)    					
    					->as_object()
    					->execute();
    	$page_links = $pagination->render();
    	
    	$href = $this->href($catalogue_id);
    	
    	$this->template->content = View::factory('admin/product/product')
    									->set('id', $catalogue_id)
    									->set('href', $href)
    									->set('page_links', $page_links)
    									->set('products', $products);
    }
    
    public function action_product_add()
    {
    	$this->template->content = View::factory('admin/product/form')
    									->set('title', 'Добавление товара')
    									->set('product', array('catalogue_id' => Arr::get($_REQUEST, 'id', '')));
    }
    
	public function action_product_edit()
    {
    	$id = Arr::get($_REQUEST, 'id', 0);
    	
    	$product = ORM::factory('product', $id)->as_array();
    	
    	$this->template->content = View::factory('admin/product/form')
    					->set('title', 'Редактирование товара')
    					->set('product', $product);
    }
    
    public function action_product_save()
    {
    	$this->auto_render = false;
        
        $id = Arr::get($_POST, 'id', '');
        
        if(!empty($id))
            $product = ORM::factory('product', $id);
        else
            $product = ORM::factory('product');
            
        $product->values($_POST);        
        try
        {           
            $product->save();
            
            if(empty($id)){
                 DB::query(Database::UPDATE, "UPDATE `product_images` SET `product_id`=:product_id WHERE `product_id` IS NULL")
                    ->param(':product_id', $product->pk())
                    ->execute();
             }

            $response = array('status' => 'ok');
        }
        catch(Kohana_ORM_Validation_Exception $e)
        {
            $errors = $e->errors('/admin');
            $response = array('status' => 'error',
                              'error' => $errors);
        }
     
        $this->response->body(json_encode($response));  
    }
    
    public function action_product_del()
    {
    	$this->auto_render = false;
    	
    	$id = Arr::get($_REQUEST, 'id', 0);
        try 
        {
        ORM::factory('product', $id)->delete();
        }
        catch (Exception $e)
        {}
    	
    	Request::$initial->redirect(Request::$initial->referrer());

    }
    
    public function action_product_images()
    {
        $this->auto_render = false;
        
        $id = Arr::get($_REQUEST, 'id', 0);
        $response = array();
        
        if($id)
            $files = DB::query(Database::SELECT, "SELECT `file` FROM `product_images` WHERE `product_id`=$id")
                            ->execute();
        else
            $files = DB::query(Database::SELECT, "SELECT `file` FROM `product_images` WHERE `product_id` IS NULL")
                            ->execute();
        
        foreach($files as $file){
            $path = Kohana::$config->load('products')->get('image_path');
            $src = $path.$file['file'];
            $response[] = str_replace('.', '_min.', $src);
        }
        
        $this->response->body(json_encode($response));
                      
        
    }
    
    public function action_product_image_delete()
    {
        $this->auto_render = false;
        
        if(Request::$initial->is_ajax()){
	    $src = Arr::get($_POST, 'src', '');
	    if(!empty($src)){
                $targetFile = '.'.$src;
		unlink($targetFile);

		$targetFile = str_replace('_min', '', $targetFile);
		unlink($targetFile);
                
                $pathinfo = pathinfo(str_replace('_min', '', $src));
                $file = $pathinfo['filename'].'.'.$pathinfo['extension'];
                DB::query(Database::DELETE, "DELETE FROM `product_images` WHERE `file`=:file LIMIT 1")
                        ->param(':file', $file)
                        ->execute();
	    }
	}
    }
    
     public function action_product_image_upload()
     {
        $this->auto_render = false;
        
        $products_config = Kohana::$config->load('products');
        
        $allowedExtensions = array();
        $sizeLimit = 2 * 1024 * 1024;

        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);      
        
        $result = $uploader->handleUpload('.'.$products_config->get('image_path'));
        
        
        if($result['success']){            
            $image = Image::factory($result['filename']);	    
            $width = $products_config->get('image_min_width');
	    $height = $products_config->get('image_min_height');
	    $wh = $width / $height;
	    $image_wh = $image->width / $image->height;
	    if($wh > $image_wh)
		$image->crop($image->width, $image->width / $wh);
	    else
		$image->crop($image->height * $wh, $image->height);
	    $image->resize($width);
	    
	    $ext = pathinfo($result['filename'], PATHINFO_EXTENSION);            
            $targetFile =  str_replace(".$ext", "_min.$ext", $result['filename']);
	    $image->save($targetFile);
            
            /*
            $image = Image::factory($result['filename']); 
            $mark = Image::factory('./images/watermark.png');

            $mark_per_x = floor($image->width / $mark->width);
            $mark_per_y = floor($image->height / $mark->height);

            $start_x = round(($image->width - $mark_per_x*$mark->width) / 2);
            $start_y = round(($image->height - $mark_per_y*$mark->height) / 2);

            for($x = 0; $x < $mark_per_x; $x++)
                for($y = 0; $y < $mark_per_y; $y++)
                    $image->watermark($mark, $start_x + $x*$mark->width, $start_y + $y*$mark->height);

            $image->save();
            */
            
            $id = (Arr::get($_GET, 'id', 0)) ? $_GET['id'] : NULL;
            $pathinfo = pathinfo($result['filename']);
            $file = $pathinfo['filename'].'.'.$pathinfo['extension'];           
            
           
            DB::query(Database::INSERT, "INSERT INTO `product_images` VALUES(NULL, :product_id,  NULL, :file)")
               ->param(':product_id', $id)
               ->param(':file', $file)
               ->execute();  
       }

       $this->response->body(htmlspecialchars(json_encode($result), ENT_NOQUOTES));
        
    }
    
    public function href($id)
    {
    	$catalogue = ORM::factory('catalogue', $id);
    	if($catalogue->loaded()){
    		return $this->href($catalogue->parent_id).$catalogue->href;	
    	} else
    		return '';
    }
}